<template>
  <PageCard title="SVG图片生成">
    <div class="svg-generate-container">
      <n-tabs v-model:value="generateMode" type="segment" animated>
        <n-tab-pane name="template" tab="使用模板">
          <div class="template-section">
            <n-space vertical :size="20">
              <div class="template-selector">
                <h4 class="section-title">选择模板</h4>
                <n-grid :cols="gridCols" :x-gap="12" :y-gap="12">
                  <n-grid-item
                    v-for="template in templates"
                    :key="template.id"
                    @click="selectTemplate(template)"
                  >
                    <div
                      class="template-card"
                      :class="{ active: selectedTemplate?.id === template.id }"
                    >
                      <div class="template-name">{{ template.name }}</div>
                      <div class="template-desc">{{ template.description }}</div>
                      <div class="template-info">
                        <span>默认尺寸: {{ template.defaultWidth }}×{{ template.defaultHeight }}</span>
                        <span>比例: {{ template.defaultRatio }}</span>
                      </div>
                    </div>
                  </n-grid-item>
                </n-grid>
              </div>
            </n-space>
          </div>
        </n-tab-pane>
        
        <n-tab-pane name="custom" tab="自定义生成">
          <div class="custom-section">
            <n-form-item label="自定义提示词">
              <n-input
                v-model:value="customPrompt"
                type="textarea"
                :rows="4"
                placeholder="请详细描述您想要的SVG样式，如：创建一个极简主义风格的SVG学习卡片，使用黑白配色，包含标题、3个核心概念和一个示例代码块"
              />
            </n-form-item>
          </div>
        </n-tab-pane>
      </n-tabs>
      
      <n-divider />
      
      <n-form label-placement="left" :label-width="100">
        <n-form-item label="生成内容" required>
          <n-input
            v-model:value="content"
            placeholder="请输入要生成的内容，如：机器学习入门、remember单词等"
          />
        </n-form-item>
        
        <n-grid :cols="3" :x-gap="12">
          <n-grid-item>
            <n-form-item label="图片比例">
              <n-select
                v-model:value="ratio"
                :options="ratioOptions"
                placeholder="使用默认比例"
              />
            </n-form-item>
          </n-grid-item>
          
          <n-grid-item>
            <n-form-item label="宽度(px)">
              <n-input-number
                v-model:value="width"
                :min="100"
                :max="2000"
                placeholder="使用默认宽度"
              />
            </n-form-item>
          </n-grid-item>
          
          <n-grid-item>
            <n-form-item label="高度(px)">
              <n-input-number
                v-model:value="height"
                :min="100"
                :max="2000"
                placeholder="使用默认高度"
              />
            </n-form-item>
          </n-grid-item>
        </n-grid>
      </n-form>
      
      <div class="action-bar">
        <n-button
          type="primary"
          size="large"
          @click="generateSVG"
          :loading="generating"
          :disabled="!canGenerate"
        >
          <template #icon>
            <n-icon>
              <svg viewBox="0 0 24 24">
                <path fill="currentColor" d="M5 19h14V5H5v14m0 2c-1.1 0-2-.9-2-2V5c0-1.1.9-2 2-2h14c1.1 0 2 .9 2 2v14c0 1.1-.9 2-2 2H5zm7-17v2h5v5h2V3h-7zm-2 4H7v7h2v-5h3V7z"/>
              </svg>
            </n-icon>
          </template>
          生成SVG
        </n-button>
        <n-button
          size="large"
          @click="reset"
          :disabled="generating"
        >
          重置
        </n-button>
      </div>
      
      <n-divider v-if="svgContent || generating" />
      
      <div v-if="svgContent || generating" class="result-section">
        <div class="result-header">
          <h3>生成结果</h3>
          <n-space v-if="svgContent && !generating">
            <n-button text @click="copySVG">
              <template #icon>
                <n-icon>
                  <svg viewBox="0 0 24 24">
                    <path fill="currentColor" d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"/>
                  </svg>
                </n-icon>
              </template>
              复制代码
            </n-button>
            <n-button text @click="downloadSVG">
              <template #icon>
                <n-icon>
                  <svg viewBox="0 0 24 24">
                    <path fill="currentColor" d="M19 12v7H5v-7H3v7c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2v-7h-2zm-6 .67l2.59-2.58L17 11.5l-5 5-5-5 1.41-1.41L11 12.67V3h2v9.67z"/>
                  </svg>
                </n-icon>
              </template>
              下载SVG
            </n-button>
          </n-space>
        </div>
        
        <n-spin :show="generating">
          <template #description>
            正在生成SVG图片，请稍候...
          </template>
          <div class="result-content">
            <n-tabs v-if="svgContent" v-model:value="viewMode" type="line">
              <n-tab-pane name="preview" tab="预览">
                <div class="markdown-preview" v-html="renderedMarkdown"></div>
              </n-tab-pane>
              <n-tab-pane name="svg" tab="SVG预览">
                <div class="svg-preview" v-html="extractedSVG"></div>
              </n-tab-pane>
              <n-tab-pane name="code" tab="原始内容">
                <n-code :code="svgContent" language="markdown" />
              </n-tab-pane>
            </n-tabs>
            <div v-else class="empty-state">
              <p>SVG图片将在这里显示</p>
            </div>
          </div>
        </n-spin>
      </div>
    </div>
    
    <n-alert
      v-if="error"
      type="error"
      closable
      @close="error = ''"
      class="error-alert"
    >
      {{ error }}
    </n-alert>
    
    <n-divider />
    
    <UsageGuide
      :title="usageGuideConfig.title"
      :steps="usageGuideConfig.steps"
      :tips="usageGuideConfig.tips"
      :example="usageGuideConfig.example"
    />
  </PageCard>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import {
  NInput,
  NButton,
  NSelect,
  NIcon,
  NDivider,
  NSpin,
  NAlert,
  NForm,
  NFormItem,
  NGrid,
  NGridItem,
  NTabs,
  NTabPane,
  NInputNumber,
  NSpace,
  NCode,
  useMessage
} from 'naive-ui'
import PageCard from '@/components/PageCard.vue'
import UsageGuide from '@/components/UsageGuide.vue'
import { SVGApi } from '@/api/utility/svg'
import { SSEClient } from '@/utils/sse'
import { useBreakpoint } from '@/utils/responsive-helper'
import MarkdownIt from 'markdown-it'
import hljs from 'highlight.js/lib/core'
import xml from 'highlight.js/lib/languages/xml'

hljs.registerLanguage('xml', xml)
hljs.registerLanguage('svg', xml)

interface Template {
  id: number
  name: string
  description: string
  defaultRatio: string
  defaultWidth: number
  defaultHeight: number
}

const message = useMessage()
const { isMobile, isTablet, isDesktop } = useBreakpoint()

const generateMode = ref<'template' | 'custom'>('template')
const templates = ref<Template[]>([])
const selectedTemplate = ref<Template | null>(null)
const customPrompt = ref('')
const content = ref('')
const ratio = ref<string | null>(null)
const width = ref<number | null>(null)
const height = ref<number | null>(null)
const generating = ref(false)
const svgContent = ref('')
const viewMode = ref<'preview' | 'svg' | 'code'>('preview')
const error = ref('')

// Markdown渲染器配置
const md = new MarkdownIt({
  html: true,
  linkify: true,
  typographer: true,
  highlight: function (str, lang) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return hljs.highlight(str, { language: lang }).value
      } catch (__) {}
    }
    return ''
  }
})

// 渲染后的Markdown内容
const renderedMarkdown = computed(() => {
  if (!svgContent.value) return ''
  return md.render(svgContent.value)
})

// 从Markdown中提取SVG代码
const extractedSVG = computed(() => {
  if (!svgContent.value) return ''
  
  // 使用正则表达式提取SVG代码块
  const svgMatch = svgContent.value.match(/```svg\n([\s\S]*?)```/)
  if (svgMatch && svgMatch[1]) {
    return svgMatch[1].trim()
  }
  
  // 如果没有代码块，尝试直接匹配SVG标签
  const directSvgMatch = svgContent.value.match(/<svg[\s\S]*?<\/svg>/)
  if (directSvgMatch) {
    return directSvgMatch[0]
  }
  
  return ''
})

const gridCols = computed(() => {
  if (isMobile.value) return 1
  if (isTablet.value) return 2
  return 3
})

// UsageGuide configuration
const usageGuideConfig = {
  title: '使用说明',
  steps: [
    '选择预设模板或使用自定义模式',
    '输入要生成的内容（如知识点、单词等）',
    '调整图片尺寸和比例（可选）',
    '点击生成按钮，等待AI创建SVG图片',
    '下载或复制生成的SVG代码'
  ],
  tips: [
    '预设模板已优化特定场景，推荐优先使用',
    '自定义模式需要详细描述SVG样式要求',
    '生成过程需要10-30秒，请耐心等待',
    '可实时预览生成效果，支持SVG代码编辑'
  ],
  example: '选择\'小红书风格知识卡片\'模板，输入\'Vue3响应式原理\'，生成精美的知识分享卡片'
}

const ratioOptions = [
  { label: '1:1 (正方形)', value: '1:1' },
  { label: '3:4 (小红书)', value: '3:4' },
  { label: '4:3 (横版)', value: '4:3' },
  { label: '4:5 (竖版)', value: '4:5' },
  { label: '16:9 (宽屏)', value: '16:9' },
  { label: '9:16 (抖音)', value: '9:16' }
]

const canGenerate = computed(() => {
  if (!content.value.trim()) return false
  if (generateMode.value === 'template') {
    return !!selectedTemplate.value
  } else {
    return !!customPrompt.value.trim()
  }
})

const selectTemplate = (template: Template) => {
  selectedTemplate.value = template
  if (!ratio.value) {
    ratio.value = template.defaultRatio
  }
  if (!width.value) {
    width.value = template.defaultWidth
  }
  if (!height.value) {
    height.value = template.defaultHeight
  }
}

const loadTemplates = async () => {
  try {
    const res = await SVGApi.getTemplates()
    templates.value = res.data
    if (templates.value.length > 0 && !selectedTemplate.value) {
      selectTemplate(templates.value[0])
    }
  } catch (err: any) {
    error.value = '加载模板失败: ' + (err.message || '未知错误')
  }
}

const generateSVG = async () => {
  if (!canGenerate.value) return
  
  generating.value = true
  error.value = ''
  svgContent.value = ''
  
  try {
    const params: any = {
      content: content.value
    }
    
    if (generateMode.value === 'template' && selectedTemplate.value) {
      params.type = selectedTemplate.value.name
    } else {
      params.prompt = customPrompt.value
    }
    
    if (ratio.value) params.ratio = ratio.value
    if (width.value) params.width = width.value
    if (height.value) params.height = height.value
    
    const reader = await SVGApi.generateSVG(params)
    
    await SSEClient.processStream(reader, {
      targetRef: svgContent,
      clearBeforeStart: true,
      onError: (err) => {
        error.value = err.message || '生成失败，请稍后重试'
      },
      onComplete: () => {
        // 生成完成后自动切换到SVG预览标签
        if (extractedSVG.value) {
          viewMode.value = 'svg'
        }
      }
    })
  } catch (err: any) {
    error.value = err.message || '生成失败，请稍后重试'
  } finally {
    generating.value = false
  }
}

const copySVG = async () => {
  try {
    const svgCode = extractedSVG.value
    if (!svgCode) {
      message.warning('没有找到SVG代码')
      return
    }
    await navigator.clipboard.writeText(svgCode)
    message.success('SVG代码已复制到剪贴板')
  } catch {
    message.error('复制失败')
  }
}

const downloadSVG = () => {
  const svgCode = extractedSVG.value
  if (!svgCode) {
    message.warning('没有找到SVG代码')
    return
  }
  const blob = new Blob([svgCode], { type: 'image/svg+xml' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `svg-${Date.now()}.svg`
  a.click()
  URL.revokeObjectURL(url)
  message.success('下载成功')
}

const reset = () => {
  content.value = ''
  customPrompt.value = ''
  svgContent.value = ''
  ratio.value = null
  width.value = null
  height.value = null
  error.value = ''
  viewMode.value = 'preview'
}

onMounted(() => {
  loadTemplates()
})
</script>

<style scoped lang="less">
@import 'highlight.js/styles/github.css';
.svg-generate-container {
  max-width: 1200px;
  margin: 0 auto;
}

.section-title {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 500;
  color: #333;
  
  @media (prefers-color-scheme: dark) {
    color: #e0e0e0;
  }
}

.template-card {
  padding: 16px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #fff;
  
  &:hover {
    border-color: var(--primary-color);
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(255, 105, 180, 0.15);
  }
  
  &.active {
    border-color: var(--primary-color);
    background: rgba(255, 105, 180, 0.05);
  }
  
  .template-name {
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 8px;
    color: #333;
  }
  
  .template-desc {
    font-size: 14px;
    color: #666;
    margin-bottom: 12px;
    line-height: 1.5;
  }
  
  .template-info {
    display: flex;
    justify-content: space-between;
    font-size: 12px;
    color: #999;
    
    @media (max-width: 768px) {
      flex-direction: column;
      gap: 4px;
    }
  }
  
  @media (prefers-color-scheme: dark) {
    background: rgba(255, 255, 255, 0.05);
    border-color: #444;
    
    &:hover,
    &.active {
      border-color: var(--primary-color);
    }
    
    .template-name {
      color: #e0e0e0;
    }
    
    .template-desc {
      color: #aaa;
    }
  }
}

.custom-section {
  padding: 20px 0;
}

.action-bar {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin: 24px 0;
}

.result-section {
  margin-top: 24px;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  
  h3 {
    margin: 0;
    font-size: 18px;
    color: #333;
    
    @media (prefers-color-scheme: dark) {
      color: #e0e0e0;
    }
  }
}

.result-content {
  min-height: 300px;
  background: #f5f5f5;
  border-radius: 8px;
  padding: 20px;
  
  @media (prefers-color-scheme: dark) {
    background: rgba(255, 255, 255, 0.05);
  }
}

.markdown-preview {
  padding: 20px;
  background: white;
  border-radius: 8px;
  min-height: 400px;
  overflow: auto;
  
  :deep(h1, h2, h3, h4, h5, h6) {
    margin-top: 24px;
    margin-bottom: 16px;
    font-weight: 600;
    line-height: 1.25;
  }
  
  :deep(h1) { font-size: 2em; }
  :deep(h2) { font-size: 1.5em; }
  :deep(h3) { font-size: 1.25em; }
  
  :deep(p) {
    margin-bottom: 16px;
    line-height: 1.6;
  }
  
  :deep(ul, ol) {
    margin-bottom: 16px;
    padding-left: 2em;
  }
  
  :deep(li) {
    margin-bottom: 8px;
  }
  
  :deep(code) {
    padding: 0.2em 0.4em;
    background: rgba(255, 105, 180, 0.1);
    border-radius: 3px;
    font-size: 85%;
  }
  
  :deep(pre) {
    padding: 16px;
    background: #f6f8fa;
    border-radius: 6px;
    overflow-x: auto;
    
    code {
      padding: 0;
      background: none;
      font-size: 100%;
    }
  }
  
  :deep(blockquote) {
    padding: 0 1em;
    color: #666;
    border-left: 0.25em solid #dfe2e5;
    margin: 0 0 16px 0;
  }
  
  @media (prefers-color-scheme: dark) {
    background: #1a1a1a;
    
    :deep(pre) {
      background: #2d2d2d;
    }
    
    :deep(code) {
      background: rgba(255, 105, 180, 0.2);
    }
    
    :deep(blockquote) {
      color: #aaa;
      border-left-color: #4a4a4a;
    }
  }
}

.svg-preview {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  min-height: 400px;
  overflow: auto;
  
  :deep(svg) {
    max-width: 100%;
    height: auto;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }
  
  @media (prefers-color-scheme: dark) {
    background: #1a1a1a;
  }
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
  color: #999;
  font-size: 16px;
}

.error-alert {
  margin-top: 16px;
}

@media (max-width: 768px) {
  .action-bar {
    flex-direction: column;
    
    .n-button {
      width: 100%;
    }
  }
}
</style>